package com.xavier.dong.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;

/**
 * @author XavierDong
 **/
public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

        byte[] bytes = new byte[msg.readableBytes()];

        msg.readBytes(bytes);
        // 将 Buffer 转为 字符串
        String message = new String(bytes, CharsetUtil.UTF_8);
        System.out.println("服务器端接收到数据 " + message);
        System.out.println("服务器端接收到的消息量=" + (++this.count));

        // 服务器 回复 一些数据 给 客户端, 回送一个 随机 id
        ByteBuf response = Unpooled.copiedBuffer(UUID.randomUUID().toString()+" ", CharsetUtil.UTF_8);
        ctx.writeAndFlush(response);


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
